package com.holystone.orca.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.holystone.orca.common.JSONMapper;
import com.holystone.orca.common.PageData;
import com.holystone.orca.sys.common.SystemConstant;
import com.holystone.orca.sys.mybatis.model.SysLookupCde;
import com.holystone.orca.sys.mybatis.model.SysLookupType;
import com.holystone.orca.sys.service.ISysLookupCodeService;
import com.holystone.orca.sys.service.ISysLookupTypeService;

/**
 * desc : 
 * 
 * @author ligang
 */
@Controller
@RequestMapping(value = "/sys/lookup_management")
public class SysLookupCodeController{

private static Logger logger = Logger.getLogger(SysLookupCodeController.class);
	
    private String baseUrl = "/sys/lookup_management";

	@Resource(name="sysLookupCodeService")
	private ISysLookupCodeService sysLookupCodeService;
	@Resource(name="sysLookupTypeService")
	private ISysLookupTypeService sysLookupTypeService;
	
	/**
	 * @author: 李刚
	 * 初始化属性集基本类型
	 */
	@RequestMapping(value="/initlookupcde")
	public ModelAndView initBase( String  iPageNo, String iPageSize,String lookupType){

        int pageindex = iPageNo!=null?Integer.parseInt(iPageNo):SystemConstant.default_pageNum;
        int pagesize = iPageSize!=null?Integer.parseInt(iPageSize):SystemConstant.default_pageSize;
        ModelAndView model = new ModelAndView("sys/lookup_management/lookupCod_management");
        try{
            PageData pageData = sysLookupCodeService.pagingSysLookupCde(pageindex, pagesize,"lookup_type",lookupType);
            model.addObject("data",pageData);
        }catch(Exception e){
            logger.error(e,e);
        }
        return model;
	}
	
	/**
	 * @author: 李刚
	 * 分页查询资源类型
	 */
	@ResponseBody
	@RequestMapping(value="/pagingLookup")
	public ModelMap pagingLookup(String iPageNo, String iPageSize,String keyword,String lookupType){
        int pageindex = iPageNo!=null?Integer.parseInt(iPageNo):SystemConstant.default_pageNum;
        int pagesize = iPageSize!=null?Integer.parseInt(iPageSize):SystemConstant.default_pageSize;
		PageData pageData =null;
        try{
            pageData= sysLookupCodeService.pagingSysLookupCde( pageindex, pagesize,"lookup_type",lookupType);
        }catch(Exception e){
            logger.error(e,e);
        }
		return JSONMapper.createReturnMap(null, pageData, null);
	}
	
	/**
	 * 初始化此类型绑定关系修改页面
	 * @author: 李刚
	 * @param sysLookupCde  关系对象
	 * @param opera  操作类型  add edit
	 * @return ModelAndView
	 */
	@RequestMapping(value="/initEditSysLookupCde")
	public ModelAndView initEditSysLookupCde(SysLookupCde sysLookupCde,String opera){
		logger.debug(">>>initEditSysLookupCde(SysLookupCde sysLookupCde)初始化码表添加修改页面");
		ModelAndView view = new ModelAndView(baseUrl+"/editLookupCod");
		List<SysLookupType> syslookupTypes = sysLookupTypeService.selectAllList();
		view.addObject("SysLookupTypes", syslookupTypes);
		if(opera!=null&&opera.equals("add")){//添加
			
		}else if(opera!=null&&opera.equals("edit")){//修改
			SysLookupCde sysLookupCdenow = sysLookupCodeService.selSysLookupCde(sysLookupCde);
			view.addObject("sysLookupCde_edit", sysLookupCdenow);
		}
		logger.debug("<<<initEditSysLookupCde(CmdbCiRelation ciRelation)");
		return view;
	}
	
	
	/**
	 * 新增码表
	 * @author: 李刚
	 * @date: 2015年11月11日 
	 * @param sysLookupCde  码表信息
	 * @param opera 操作类型  add edit
	 * @return ModelMap
	 */
	@ResponseBody
	@RequestMapping(value="/editLookupCode")
	public ModelMap editLookupCode(SysLookupCde sysLookupCde,String opera){
		logger.debug(">>>addCiType(SysLookupCde sysLookupCde)新增码表 ,参数sysLookupCde="+sysLookupCde.toString());
		ModelMap map = new ModelMap();
        try{
            if(opera!=null&&opera.equals("add")){//添加
                sysLookupCde.getLookupType();
			/*
			 * 計算出code值
			 */
                List<SysLookupCde> list= sysLookupCodeService.getLookupCdeByType(sysLookupCde.getLookupType());
                String lookupType=null;
                int lookupTypeNum=0;
                int lookupTypeNumNow = 0;
                for(SysLookupCde s : list){
                    if(lookupType==null)
                        lookupType = s.getLookupCode().substring(0, s.getLookupCode().length()-1);
                    if(s.getLookupCode()!=null&& !s.getLookupCode().equals("")){
                        lookupTypeNum = (int)s.getLookupCode().charAt(s.getLookupCode().length()-1);
                        if(lookupTypeNumNow<=lookupTypeNum){
                            lookupTypeNumNow=lookupTypeNum+1;
                        }
                    }
                }
                sysLookupCde.setLookupCode(lookupType+((char)lookupTypeNumNow));
                map.put("flag", sysLookupCodeService.addSysLookupCde(sysLookupCde));
                logger.debug("<<<addSysLookupCde(CmdbCiType ciType)返回结果ModelMap="+map.toString());
            }else if(opera!=null&&opera.equals("edit")){//修改
                int result=sysLookupCodeService.updateAll(sysLookupCde);
                map.put("flag", result);
                logger.debug("<<<editSysLookupCde(CmdbCiType ciType)返回结果ModelMap="+map.toString());
            }
        }catch(Exception e){
            logger.error(e,e);
        }
		return map;
	}/**
	 * 删除码表
	 * @author: fengt
	 * @date: 2015年11月17日
	 * @param sysLookupCde  码表信息
	 * @return ModelMap
	 */
	@ResponseBody
	@RequestMapping(value="/deleteLookupcde")
	public ModelMap deleteLookupcde(SysLookupCde sysLookupCde){
		logger.debug(">>>deleteLookupcde(SysLookupCde sysLookupCde)删除码表 ,参数sysLookupCde="+sysLookupCde.toString());
		ModelMap map = new ModelMap();
        try{
            sysLookupCde.setCdeFlag(0);
            int result=sysLookupCodeService.updateSysLookupFlag(sysLookupCde);
            map.put("flag", result);
               logger.debug("<<<deleteLookupcde(CmdbCiType ciType)返回结果ModelMap="+map.toString());
        }catch(Exception e){
            logger.error(e,e);
        }
		return map;
	}
	/**
	 * 树状显示码表界面
	 * @author: yangfh
	 * @date: 2017年3月20日 
	 * @return ModelAndView
	 */
	@RequestMapping(value="/initSysLookupCodeTypeManagement")
	public ModelAndView lookupManage(){
		ModelAndView view = new ModelAndView(baseUrl+"/lookupCodeType_management");
		return view;
	}
	
	/**
	 * 初始化码表树
	 * @author: yangfh
	 * @date: 2017年3月20日
	 * @param syslookupTypes码表类型集合 
	 * @param nodes 返回的json串
	 * @return ModelMap
	 */
	@ResponseBody
	@RequestMapping(value="initSysLookupCodeTypeTree")
	public ModelMap initCodeTypeTree(){
		ModelMap modelMap=new ModelMap();
		//根据码表类型
		List<SysLookupType> syslookupTypes = sysLookupTypeService.selectAllList();
		String nodes = "";
		for(int i=0;i<syslookupTypes.size();i++){
			nodes +="{id:\'"+syslookupTypes.get(i).getLookupType()+"\',pId:0"+", \"name\":\'"
					+syslookupTypes.get(i).getLookupDesc()+"\'"
					+",open:true},";
		}
		if(nodes != ""){
			nodes = nodes.substring(0, nodes.length() - 1);
		}
		nodes ="["+nodes+"]";
		modelMap.put("lstTree", nodes);
		
		return modelMap;
	}
	/**
	 * 树状显示码表界面
	 * @author: yangfh
	 * @date: 2017年3月20日 
	 * @return ModelAndView
	 */
	@ResponseBody
	@RequestMapping(value="lookupTreeManagement")
	public ModelMap lookupTreeManagement(String  iPageNo, String iPageSize,String type){
		ModelMap modelMap=new ModelMap();
		int pageindex = iPageNo!=null?Integer.parseInt(iPageNo):SystemConstant.default_pageNum;
        int pagesize = iPageSize!=null?Integer.parseInt(iPageSize):SystemConstant.default_pageSize;
        PageData pageData =null;
        List<SysLookupType> syslookupTypes = sysLookupTypeService.selectAllList();
		for(SysLookupType st:syslookupTypes)
		{
			if(type.equals(st.getLookupDesc())){
				try {
					List<SysLookupCde> sl=sysLookupCodeService.selectCdeByType(st.getLookupType());
					pageData = sysLookupCodeService.pagingSysLookupCde(pageindex, pagesize,"lookup_type",st.getLookupType());
				} catch (Exception e) {
					logger.error(e,e);
				}
			}
		}
		return JSONMapper.createReturnMap(null, pageData, null);
	}
	
	/**
	 * 自动填充码表类型的codeSelect
	 * @author: 齐俊星
	 * @date: 2017年4月17日
	 * @param syslookupTypes码表类型集合 
	 * @param  返回的json串
	 * @return ModelMap
	 */
	@ResponseBody
	@RequestMapping(value="easySelect")
	public ModelMap easySelect(String selectType){
		ModelMap modelMap=new ModelMap();
		//根据码表类型
		List<List<SysLookupCde>>  list=new  ArrayList<List<SysLookupCde>>();
		String[]    type=selectType.split(",");
		for (String string : type) {
			List<SysLookupCde> sysLookupTypelist=sysLookupCodeService.getLookupCdeByType(string);
			list.add(sysLookupTypelist);
			}
		
		modelMap.put("codeSelect", list);
		return modelMap;
	}
}
